package cn.huiyunche.driver.schedule;

import cn.huiyunche.base.service.constant.TmsUrlConstant;
import cn.huiyunche.base.service.enums.TmsUrlTypeEnum;
import cn.huiyunche.base.service.interfaces.TmsOrderCallHistoryService;
import cn.huiyunche.base.service.model.TmsOrder;
import cn.huiyunche.base.service.utils.DateUtils;
import cn.huiyunche.driver.service.OrderService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections4.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 获取订单定时任务
 *
 * @author hdy
 */
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public class ImportOrdersQuartzCluster implements Job, Serializable {

    private static final long serialVersionUID = 1L;

    private static final Logger LOGGER = LoggerFactory.getLogger(ImportOrdersQuartzCluster.class);

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        LOGGER.info("ImportOrdersQuartzCluster.execute start : {}", new DateTime().toString(DateUtils.YYYY_MM_DD_HH_MM_SS_SSS));

        final String url = TmsUrlConstant.PULL_IMPORT;
//        final String url = "http://222.126.229.155/dti/order/fetch2";

//        final String url = "http://localhost:3000/order";

        TmsOrderCallHistoryService tmsOrderCallHistoryService = QuartzClusterFactory.getTmsOrderCallHistoryService();

        //查询上一次成功url调用成功的记录
        Date lastTime = tmsOrderCallHistoryService.getLastTimeSuccess(TmsUrlTypeEnum.PULL_IMPORT.getValue(), true);

        Map<String, Object> paramsMap = new HashedMap<>();
        //DateTime datatime = new DateTime(2016, 12, 20, 00, 00,00);
        paramsMap.put("lastTime", new DateTime(lastTime).toString(DateUtils.YYYY_MM_DD_HH_MM_SS_SSS));
        LOGGER.info("ImportOrdersQuartzCluster.execute interface query time : {}", lastTime);

        String result = tmsOrderCallHistoryService.urlCall(url, TmsUrlTypeEnum.PULL_IMPORT.getValue(), paramsMap, 30000);
        if (StringUtils.isNotBlank(result)) {
            JSONObject jsonObject = JSONObject.parseObject(result);
            String data = jsonObject.getString("data");
            if (StringUtils.isNotBlank(data)) {
                List<TmsOrder> tmsOrders = JSONArray.parseArray(data, TmsOrder.class);

                LOGGER.info("ImportOrdersQuartzCluster.execute handleTmsOrders tms orders : {}", tmsOrders);

                OrderService orderService = QuartzClusterFactory.getOrderService();
                orderService.handleTmsOrders(tmsOrders);
            }
        }
        LOGGER.info("ImportOrdersQuartzCluster.execute end time : {}", new DateTime().toString(DateUtils.YYYY_MM_DD_HH_MM_SS_SSS));
    }

}
